<script src="/static/vue/vue.js"></script>
<script src="/static/vue-qr-reader/vue-qr-reader.js"></script>
<link rel="stylesheet" href="/static/vue-element/vue-element.css">
<script src="/static/vue-element/vue-element.js"></script>
<script src="/static/string-format.js"></script>
<script src="/static/html-util.js"></script>
<style>
    div.selectize-input{
        width: fit-content;
    }
</style>

<div id="scanner">

    <div class="form-inline">
        <button type="button" class="btn btn-default" @click="scan">
            <span class="glyphicon glyphicon-qrcode" aria-hidden="true" ></span>
        </button>
        <select  v-model="selected" name="{{ widget.name }}" {% include "django/forms/widgets/attrs.html" %}>
            {% for group_name, group_choices, group_index in widget.optgroups %}
                {% if group_name %}
                    <optgroup label="{{ group_name }}">{% endif %}
            {% for option in group_choices %}
                {#                        {% include option.template_name with widget=option %}#}
                <option value="{{ option.value|stringformat:'s' }}" {% include "django/forms/widgets/attrs.html" %}
                        selected="selected">{{ option.label }}</option>
            {% endfor %}
            {% if group_name %}</optgroup>{% endif %}
            {% endfor %}
        </select>

    </div>


    <el-dialog
            id="dialog"
            title="扫一扫"
            :visible.sync="dialogVisible"
            width="90%"
            :before-close="handleClose">

        <!--vue-qr-reader-->
        <div v-if="scanned!=''">Scanned Value: {vue{ scanned }vue}</div>
        <div v-if="errorMessage != ''">Scan Error: {vue{ errorMessage }vue}</div>
        <div v-if="result['exist']">Feedback: {vue{ result['data']['label'] }vue}</div>
        <vue-qr-reader ref="qr"

                       v-on:code-scanned="codeScanned"
                       stop-on-scanned="false"
                       use-back-camera="true"
                       draw-on-found="true"
                       line-color="	#FFB6C1"
                       line-width="20"
                       video-height="480"
                       video-width="640"
                       responsive="true">
        </vue-qr-reader>
        <!--vue-qr-reader-->


        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = !dialogVisible">取 消</el-button>
            <el-button type="primary" @click="commitScanned">确 定</el-button>
            <!--只有按叉和点击对话框以外区域才触发before-close，也就要是说按叉和点击对话框以外区域等效-->
        </span>
    </el-dialog>
</div>
<script>
    // 千万注意字符型模板变量传递给js时加引号
    let originSelected = eval(
        HtmlUtil.htmlDecodeByRegExp(
            "{{ widget.value }}"  // "[&#39;86&#39;]"
        )  // "['6']"
    );  // ['6']

    originSelected = parseInt(originSelected[0]);  // 6

    originSelected = parseInt({{ widget.value | safe}}[0]);

    console.log(originSelected);

    // 获取商品的信息，optgroups_json是在forms中重载get_context方法datastructure:python -> json
    let optgroups = eval(
        HtmlUtil.htmlDecodeByRegExp("{{ optgroups_json }}")
    );
    optgroups.splice(0, 1);
    let goodInfos = [];
    for (let [groupName, group, count] of optgroups) {
        for (let goodInfo of group) {
            goodInfos.push({
                'value': goodInfo['value'],
                'label': goodInfo['label'],
            })
        }
    }
    let widget_json = {{ widget_json | safe}}

    // 判断扫描得到的code是否在商品信息中
    function scannedFeedback(scanned, records) {
        for (let record of records) {
            if (record['label'].indexOf(scanned) >= 0) {
                return {
                    'data': record,
                    'exist': true
                }
            }
        }
        return {
            'data': null,
            'exist': false
        }
    }

    function changeSelected(value) {
        let selector = formatString("div[data-value='{0}']", value);
        console.log(selector);

        $(document).ready(function () {
            // 开始写 jQuery 代码...
            $(selector).click()
        });
    }


    const scanner = new Vue({
        el: '#scanner',
        delimiters: ["{vue{", "}vue}"],
        mounted() {
            // 如果select有默认选中，当绑定了v-model后可以在挂载时赋予初值
            // 如果不用v-model并做初始化处理，update始终显示列表的最后一个商品，why!!!!!!
            this.selected = originSelected
        },
        data: function () {
            return {

                // element dialog
                dialogVisible: false,

                // vue-qr-reader
                selected: originSelected,
                scanned: '',
                errorMessage: '',
                result: {
                    'data': {
                        value: '',
                        label: ''
                    },
                    'exist': false
                }
            }
        },
        commponents: {},
        methods: {

            // element dialog
            scan() {
                this.dialogVisible = !this.dialogVisible;
                $("div[class='item']").click();
            },
            handleClose: function () {
                this.dialogVisible = !this.dialogVisible;
            },
            commitScanned() {
                this.dialogVisible = !this.dialogVisible;

                changeSelected(this.result['data']['value']);
            },

            // vue-qr-code
            codeScanned(event) {
                this.scanned = event.detail[0];
                this.result = scannedFeedback(this.scanned, goodInfos);
            },
            errorCaptured(error) {
                switch (error.name) {
                    case 'NotAllowedError':
                        this.errorMessage = 'Camera permission denied.'
                        break;
                    case 'NotFoundError':
                        this.errorMessage = 'There is no connected camera.'
                        break;
                    case 'NotSupportedError':
                        this.errorMessage = 'Seems like this page is served in non-secure context.'
                        break;
                    case 'NotReadableError':
                        this.errorMessage = 'Couldn\'t access your camera. Is it already in use?'
                        break;
                    case 'OverconstrainedError':
                        this.errorMessage = 'Constraints don\'t match any installed camera.'
                        break;
                    default:
                        this.errorMessage = 'UNKNOWN ERROR: ' + error.message
                }
                console.error(this.errorMessage);
            },
        }
    });

</script>
